# -*- coding: utf-8 -*-
# @project: huawang-api
# @file： public_methods.py
# @Time：2023/7/14 16:09
# @Author：lizhixiong


import json
import allure
import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By
from common.commin.commin import read_ini, elements_visibility, get_ele_text
from common.log.log import log
from common.request.request_api import RequestHandler, YkRequestHandler
from config.conf import BASE_DIR
import selenium.webdriver.remote.webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from time import sleep

from data.names import PublicSel
from po.jinhua.ht.api.ht_api import ht_api_send_coupons
from po.jinhua.ht.commodity_management_page.commodity_management_page import CommodityManagementPage
from po.jinhua.ht.jinhua_ht_main.jinhua_ht_main_page import JHHTHomePage

import json
import allure
import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By
from common.commin.commin import read_ini, elements_visibility, get_ele_text
from common.log.log import log
from common.request.request_api import RequestHandler, YkRequestHandler
from config.conf import BASE_DIR
import selenium.webdriver.remote.webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from time import sleep

from data.names import PublicSel
from po.jinhua.ht.commodity_management_page.commodity_management_page import CommodityManagementPage
from po.jinhua.ht.jinhua_ht_main.jinhua_ht_main_page import JHHTHomePage

"""环境url"""
yg_url = read_ini(BASE_DIR + '/config_yg.ini')['host']['url']  # 云购
yk_url = read_ini(BASE_DIR + '/config_yk.ini')['host']['url']  # 云客
test_yk_url = read_ini(BASE_DIR + '/config_yk.ini')['host']['test_url']  # 云客test环境
yc_url = read_ini(BASE_DIR + '/config_yc.ini')['host']['url']  # 云创
"""管理台账号密码"""
yg_username = read_ini(BASE_DIR + '/config_yg.ini')['host']['user']
yg_password = read_ini(BASE_DIR + '/config_yg.ini')['host']['password']
yc_username = read_ini(BASE_DIR + '/config_yc.ini')['host']['user']
yc_password = read_ini(BASE_DIR + '/config_yc.ini')['host']['password']
yk_username = read_ini(BASE_DIR + '/config_yk.ini')['host']['user']
yk_password = read_ini(BASE_DIR + '/config_yk.ini')['host']['password']

"""
#####################################################################
#######################   #############   ###########################
#####################################################################
####################   公共方法，比如登录等封装   #######################
#####################################################################
##############################    ###################################
#####################################################################
"""


@allure.step('花王云创管理台api登录')
def yc_ht_api_login():
    """
    花王云创管理台api登录
    return: 返回token
    """
    user_name = read_ini(BASE_DIR + '/config_yc.ini')['host']['user']
    password = read_ini(BASE_DIR + '/config_yc.ini')['host']['password']
    # 登录信息
    login_info = {
        "account": user_name,
        "pwd": password,
        "key": "6d1a3055f8bee884b6377233c09fd79a",
        "code": "123",
        "wxCode": ""
    }

    log.info('花王云创——管理台登录')
    req = RequestHandler('123', 'yg')
    get_url = yc_url + f'/jinhua/api/admin/login'
    response = req.visit('post', get_url, json=login_info)
    # allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
    log.info(response.text)
    result = json.loads(response.text)
    log.info('登录成功')
    return result['data']['token']


@allure.step('花王云购管理台api登录')
def yg_ht_api_login():
    """
    花王云购管理台api登录
    return: 返回token
    """
    user_name = read_ini(BASE_DIR + '/config_yg.ini')['host']['user']
    password = read_ini(BASE_DIR + '/config_yg.ini')['host']['password']
    # 登录信息
    login_info = {
        "account": user_name,
        "pwd": password,
        "key": "6d1a3055f8bee884b6377233c09fd79a",
        "code": "123",
        "wxCode": ""
    }

    log.info('花王云购——管理台登录')
    req = RequestHandler('123', 'yg')
    get_url = yg_url + f'/jinhua/api/admin/login'
    response = req.visit('post', get_url, json=login_info)
    allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
    log.info(response.text)
    result = json.loads(response.text)
    log.info('登录成功')
    return result['data']['token']


@allure.step('花王云购api接口——微信授权登录')
def yg_applets_wx_api_login():
    """
    花王云购api接口——微信授权登录
    return: 返回token
    """
    # 微信授权登录信息
    login_info = {
        "encryptedData": "pnsKKOvdvRlyLOhtDlHZi17fDr1lSqQpz2wLAiD8lSHBziXk6ZTxnejt/mGl6mArWboEU9OhA+M5Yz6x/Oy2fwMwqpO1MflPhq4p2iDhuPKQL15Gfd9j97C8jF3MeYssuPWxK6lUTSe/25FtbKDPyLmgtjRDBFrhw1KkCPK/NvPcAlMcsa8WsbUCXnBavcP4EX9BvlDWCEhix7pLWb1Rug==",
        "iv": "x9lRwBte/a7S6hKTkvRO2w==",
        "sessionKey": "2AyND8RSryiQ/GGW5F1rYw==",
        "openId": "o_BPy5dZlCK46Y_5qFiCT0TGhXgI",
        "type": "routine"
    }

    log.info('花王云购——api接口——微信授权登录')
    req = RequestHandler('123', 'yg')
    get_url = yg_url + f'/jinhua/api/front/wechat/authorize/phone/login'
    response = req.visit('post', get_url, json=login_info)
    # allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
    log.info(response.text)
    result = json.loads(response.text)
    log.info('登录成功')
    return result['data']['token']


@allure.step('花王云创api接口——微信授权登录')
def yc_applets_wx_api_login():
    """
    花王云创
    api接口——微信授权登录
    return: 返回token
    """
    # 微信授权登录信息
    login_info = {
        "encryptedData": "RNrm9O3tRO7675pqE36ZLKYCPLST6lcpDbJa1hdI32+rZ0xjJHREI7FrCPnqmJL0vErDefWqpO0hmn79x1rdWo2AFSpjek6d+sQtScpWqYeU72z4YJttxA6M4L5Bvw7d0LQBzlbqers6nghdYlED+Ioq7hyPfWoKAcOPp6uxtbOw/eBTqFu3xqcHwjyEj37Yrqs/npZyFFyU13TnOp154A==",
        "iv": "nEkiZqVRXiK2g1xRPZjRow==",
        "sessionKey": "LucZrhh16V+0TQ4A3u9m1Q==",
        "openId": "oaSG84rCDw3mMv9MHyBT1aajGUdU",
        "type": "routine"
    }

    log.info('花王云创——api接口——微信授权登录')
    req = RequestHandler('123', 'yc')
    get_url = yc_url + f'/jinhua/api/front/wechat/authorize/phone/login'
    response = req.visit('post', get_url, json=login_info)
    # allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
    log.info(response.text)
    result = json.loads(response.text)
    log.info('登录成功')
    return result['data']['token']


# @allure.step('花王云购后台ui登录')
# def yg_ui_login_backstage(mode=0):
#     log.info('登录商城后台')
#     global driver_chrome
#     if mode == 0:
#         log.info('远程docker容器启动')
#         driver_chrome = selenium.webdriver.remote.webdriver.WebDriver(
#             command_executor="http://166.166.200.50:5001/wd/hub",
#             desired_capabilities=DesiredCapabilities.CHROME
#         )
#     elif mode == 1:
#         log.info('本地启动谷歌浏览器')
#         driver_chrome = webdriver.Chrome()
#     # 初始参数配置
#     driver_chrome.implicitly_wait(15)
#     driver_chrome.delete_all_cookies()  # 为了防止污染，清空cookie
#     driver_chrome.get(yg_url + '/admin/login')
#     driver_chrome.maximize_window()
#     sleep(0.5)
#     driver_chrome.find_element(By.CSS_SELECTOR, '[name="username"]').send_keys(yg_username)
#     driver_chrome.find_element(By.CSS_SELECTOR, '[name="pwd"]').send_keys(yg_password)
#     sel = driver_chrome.find_elements(By.CSS_SELECTOR, '.el-input__inner')
#     sel[-1].clear()
#     sel[-1].send_keys('123456')
#     driver_chrome.find_element(By.CSS_SELECTOR, '.el-button--medium').click()
#     sleep(0.5)
#     return driver_chrome

@allure.step('花王云购后台ui登录')
def yg_ui_login_backstage(mode=1):
    log.info('登录商城后台')
    global driver_chrome
    if mode == 0:
        log.info('远程docker容器启动')
        driver_chrome = selenium.webdriver.remote.webdriver.WebDriver(
            command_executor="http://166.166.200.50:5001/wd/hub",
            desired_capabilities=DesiredCapabilities.CHROME
        )
    elif mode == 1:
        log.info('本地启动谷歌浏览器')
        driver_chrome = webdriver.Chrome()
    # 初始参数配置
    driver_chrome.implicitly_wait(15)
    driver_chrome.delete_all_cookies()  # 为了防止污染，清空cookie
    driver_chrome.get(yg_url + '/admin/login')
    driver_chrome.maximize_window()
    sleep(0.5)
    driver_chrome.find_element(By.CSS_SELECTOR, '[name="username"]').send_keys(yg_username)
    driver_chrome.find_element(By.CSS_SELECTOR, '[name="pwd"]').send_keys(yg_password)
    sel = driver_chrome.find_elements(By.CSS_SELECTOR, '.el-input__inner')
    sel[-1].clear()
    sel[-1].send_keys('123456')
    driver_chrome.find_element(By.CSS_SELECTOR, '.el-button--medium').click()
    sleep(0.5)
    return driver_chrome


@allure.step('花王云创后台ui登录')
def yc_ui_login_backstage(mode=0):
    log.info('登录商城后台')
    global driver_chrome
    if mode == 0:
        log.info('远程docker容器启动')
        driver_chrome = selenium.webdriver.remote.webdriver.WebDriver(
            command_executor="http://166.166.200.50:5001/wd/hub",
            desired_capabilities=DesiredCapabilities.CHROME
        )
    elif mode == 1:
        log.info('本地启动谷歌浏览器')
        driver_chrome = webdriver.Chrome()
    # 初始参数配置
    driver_chrome.implicitly_wait(15)
    driver_chrome.delete_all_cookies()  # 为了防止污染，清空cookie
    driver_chrome.get(yc_url + '/admin/login')
    log.info(f'get地址为：{yc_url}' + '/admin/login')
    driver_chrome.maximize_window()
    sleep(5)
    driver_chrome.find_element(By.CSS_SELECTOR, '[name="username"]').send_keys(yc_username)
    driver_chrome.find_element(By.CSS_SELECTOR, '[name="pwd"]').send_keys(yc_password)

    # 输入验证码并确定
    sel = driver_chrome.find_elements(By.CSS_SELECTOR, '.el-input__inner')
    sel[-1].clear()
    sel[-1].send_keys('123456')
    driver_chrome.find_element(By.CSS_SELECTOR, '.el-button--medium').click()
    sleep(3)
    return driver_chrome


@allure.step('花王云购管理台：添加商品')
def yg_add_sp(item_name):
    """
    花王云购管理台：添加商品
    """
    JHHTHomePage(driver_chrome).open_menu('yg', '商品管理')
    CommodityManagementPage(driver_chrome).add_item(item_name)


@allure.step('花王云购管理台：删除商品')
def yg_rmv_sp(item_name):
    """
    花王云购管理台：删除商品
    """
    x = CommodityManagementPage(driver_chrome).open_goods_in_warehouse().add_item_delete(item_name)[-1]
    y = CommodityManagementPage(driver_chrome).open_recycling_station().item_delete(item_name)[-1]


@allure.step('花王云客后台ui登录')
def yk_ui_login_backstage(mode=0):
    """############登录云客商城后台############"""
    log.info('登录云客商城后台')
    global driver_chrome  # 全局变量，方便失败操作的钩子函数 调用 drive，进行截图
    global key
    if mode == 0:
        log.info('远程docker容器启动')
        driver_chrome = selenium.webdriver.remote.webdriver.WebDriver(
            command_executor="http://166.166.200.50:5001/wd/hub",
            desired_capabilities=DesiredCapabilities.CHROME
        )

    elif mode == 1:
        log.info('本地启动谷歌浏览器')
        driver_chrome = webdriver.Chrome()

    driver_chrome.implicitly_wait(15)
    driver_chrome.delete_all_cookies()  # 为了防止污染，清空cookie
    driver_chrome.get(yk_url + '/admin/#/login')
    driver_chrome.maximize_window()

    retry_count = 10  # 定义重试次数
    count = 0
    for i in range(retry_count):
        # 处理验证码
        code_file = BASE_DIR + '/data/code.png'

        # login-code元素可见
        elements_visibility(driver_chrome, By.CSS_SELECTOR, ".login-code")

        img = driver_chrome.find_element(By.CSS_SELECTOR, ".login-code")  # 验证码图片
        img.screenshot(code_file)  # 下载图片
        sleep(1)
        # 利用ddddocr识别验证码
        ocr = ddddocr.DdddOcr(show_ad=False)  # show_ad 不打印广告了
        with open(code_file, "rb") as fp:
            image = fp.read()
        result = ocr.classification(image)  # 返回验证码识别结果
        log.info("=============================")
        log.info(result)

        x = result[0:1]
        y = result[2:3]
        logic = result[1:2]
        if logic == '+' and x.isdigit() and y.isdigit():
            key = int(x) + int(y)
        elif logic == '-' and x.isdigit() and y.isdigit():
            key = int(x) - int(y)
        elif logic == 'x' and x.isdigit() and y.isdigit():
            key = int(x) * int(y)
        else:
            key = '123456'

        sel = driver_chrome.find_elements(By.CSS_SELECTOR, '.el-input__inner')
        sel[0].clear()
        sel[1].clear()
        sel[2].clear()
        sel[0].send_keys(yk_username)
        sel[1].send_keys(yk_password)
        sel[2].send_keys(key)
        driver_chrome.find_element(By.CSS_SELECTOR, '.el-button--medium').click()
        sleep(3)

        success_url = driver_chrome.current_url
        log.info(success_url)
        count += 1
        if '/#/dashboard' in success_url:
            log.info('登录成功')
            sleep(2)
            break
        if count == retry_count:
            log.error(f'尝试了{retry_count}次获取验证码仍然失败，请重新检查复杂度！')
            driver_chrome.close()
            raise
    return driver_chrome


@allure.step('test环境花王云客后台ui登录')
def yk_tt_ui_login(mode=0):
    global driver
    log.info('登录云客test商城后台')
    if mode == 0:
        log.info('远程docker容器启动')
        driver = selenium.webdriver.remote.webdriver.WebDriver(
            command_executor="http://166.166.200.50:5001/wd/hub",
            desired_capabilities=DesiredCapabilities.CHROME
        )
    elif mode == 1:
        log.info('启动本地浏览器')
        driver = webdriver.Chrome()

    driver.get('http://hwyktest.huawangglobal.com/admin/#/login')
    driver.implicitly_wait(10)
    driver.maximize_window()
    count = 0
    num = 5
    # for one in range(num):
    #
    #     ele_code = driver.find_element(By.XPATH, '//div/img')
    #     with open('code.png', 'wb') as f:
    #         f.write(ele_code.screenshot_as_png)  # 写入到一个图片
    #
    #     ocr = ddddocr.DdddOcr(show_ad=False)  # 初始化一个ocr对象
    #     code = ocr.classification(ele_code.screenshot_as_png)  # 当前验证码的字符
    #     print(code[0], code[1], code[2])
    #     if code[1] == "+":
    #         res = int(code[0]) + int(code[2])
    #     elif code[1] == "-":
    #         res = int(code[0]) + int(code[2])
    #     elif code[1] == 'x':
    #         res = int(code[0]) * int(code[2])
    #     elif code[1] == '/':
    #         res = int(code[0]) / int(code[2])
    #     else:
    #         res = '123456'

    user = driver.find_element(By.XPATH, '//*[@placeholder="账号"]')
    password = driver.find_element(By.XPATH, '//*[@placeholder="密码"]')
    yzm = driver.find_element(By.XPATH, '//*[@placeholder="验证码"]')

    user.clear()
    password.clear()
    yzm.clear()

    user.send_keys('admin')
    password.send_keys('huawang333.')
    yzm.send_keys('123456')
    driver.find_element(By.CSS_SELECTOR, '[class="el-button el-button--primary el-button--medium"]').click()
    sleep(3.5)
    success_url = driver.current_url
    count += 1
    if "#/dashboard" in success_url:
        log.info('test环境登录成功')
        token = driver.get_cookies()[0]['value'].replace('%20', ' ')
        # break
    if count == num:
        log.error(f'尝试了{count}次获取验证码仍然失败，请重新检查复杂度！')
        # driver.close()
        raise
    return driver


@allure.step('花王云客管理台api登录')
def yk_ht_api_login():
    """
    test花王云客管理台api登录
    返回token
    """
    get_url = test_yk_url + '/webserver/auth/login'
    log.info('开始花王云客管理台api登录')
    login_info = {"username": "admin",
                  "password": "mcmIZ9wKWnugeKYpB8vwKsI2Bs3v1KK413w3Rrd5E/KmRtmvsAiO/RHfgywHgx/6TTmR59IqcppWZtSBJRVPgA==",
                  "code": "123456",
                  "uuid": "code-key057351d4c8734801bd104ab264241029"}

    res = YkRequestHandler('123', 'yk')
    response = res.visit('post', get_url, json=login_info)
    allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
    log.info(response.text)
    result = json.loads(response.text)  # json.loads 将数据格式转换为字典dict
    log.info('登录成功')
    return result['token']


@allure.step('断言列表文案')
def assert_sel_text_exist(drive, sel, test):
    sel_text = get_ele_text(drive, sel)
    if test in sel_text:
        return True
    else:
        return False


if __name__ == '__main__':
    # yc_ui_login_backstage()
    # yg_ui_login_backstage()
    # yk_tt_ui_login()
    # yg_ui_login_backstage()
    token = yg_ht_api_login()
    ht_api_send_coupons(token)
